package com.softstao.guoyu.ui.activity.me;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.me.AgentInfo;
import com.softstao.guoyu.model.me.RechargeCondition;
import com.softstao.guoyu.model.me.SubAgentInfo;
import com.softstao.guoyu.mvp.interactor.UploadInteractor;
import com.softstao.guoyu.mvp.interactor.me.BalanceInteractor;
import com.softstao.guoyu.mvp.presenter.UploadPresenter;
import com.softstao.guoyu.mvp.presenter.me.BalancePresenter;
import com.softstao.guoyu.mvp.viewer.UploadTargetViewer;
import com.softstao.guoyu.mvp.viewer.me.RechargeViewer;
import com.softstao.guoyu.ui.baseAdapter.CommonBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.ViewHolder;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.activity.ImagePagerActivity;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CircleImageView;
import com.softstao.softstaolibrary.library.widget.CustomGridView;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.progressBar.RoundProgressBarWidthNumber;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/7/4.
 */

public class RechargeActivity extends BaseActivity implements RechargeViewer, UploadTargetViewer {

    @AIPresenter(presenter = BalancePresenter.class, interactor = BalanceInteractor.class)
    BalancePresenter presenter;
    @AIPresenter(presenter = UploadPresenter.class, interactor = UploadInteractor.class)
    UploadPresenter uploadPresenter;

    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.pay_img_view)
    CustomGridView payImgView;
    @BindView(R.id.memo)
    EditText memo;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R.id.progress)
    RoundProgressBarWidthNumber progress;
    private int id;
    private RechargeCondition condition = new RechargeCondition();
    private SubAgentInfo subAgentInfo;
    private CommonBaseAdapter<String> imgAdapter;
    private List<String> datas = new ArrayList<>();
    public final static int IMAGE = 100;

    @Override
    public int _ContentView() {
        return R.layout.activity_recharge;
    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    @Override
    public void initView() {
        initTitle("填写充值信息");
        id = getIntent().getIntExtra("id", 0);
        money.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_SIGNED);
        money.setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) ->{
            if(source.equals(".") && dest.toString().length() == 0){
                return "0.";
            }
            if(dest.toString().contains(".")){
                int index = dest.toString().indexOf(".");
                int mlength = dest.toString().substring(index).length();
                if(mlength == 3){
                    return "";
                }
            }
            return null;
        }});

        imgAdapter = new CommonBaseAdapter<String>(datas, R.layout.layout_img) {
            @Override
            public int getCount() {
                int count;
                count = datas.size() == 0 ? 1 : datas.size() + 1;
                return count;
            }

            @Override
            public String getItem(int position) {
                if (datas.size() != 0 && position < datas.size()) {
                    return mdatas.get(position);
                }
                return null;
            }

            @Override
            public void convert(ViewHolder holder, String s) {
                if (datas.size() != 0 && holder.getmPosition() < datas.size()) {
                    Glide.with(context).load(s).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v -> imageBrower(holder.getmPosition(), (ArrayList<String>) datas));
                    holder.getView(R.id.del).setVisibility(View.VISIBLE);
                    holder.getView(R.id.del).setOnClickListener(v -> {
                        datas.remove(holder.getmPosition());
                        notifyDataSetChanged();
                    });
                } else {
                    Glide.with(context).load(R.mipmap.add_pic).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v ->
                            new RxPermissions(RechargeActivity.this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                                    .subscribe(result-> {
                                        if (result){
                                            PictureSelector.create(RechargeActivity.this)
                                                    .openGallery(PictureMimeType.ofImage())
                                                    .selectionMode(PictureConfig.SINGLE)
                                                    .previewImage(true)
                                                    .isCamera(true)
                                                    .enableCrop(true)
                                                    .freeStyleCropEnabled(true)
                                                    .forResult(IMAGE);
                                        }
                                    }));
                    holder.getView(R.id.del).setVisibility(View.GONE);
                }
            }
        };
        payImgView.setAdapter(imgAdapter);
    }

    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    private void initData() {
        if (subAgentInfo.getImg() != null && !subAgentInfo.getImg().equals("")) {
            Glide.with(context).load(subAgentInfo.getImg()).into(avatar);
        } else {
            avatar.setImageResource(R.mipmap.default_avatar);
        }
        name.setText(subAgentInfo.getName() + "（" + subAgentInfo.getLevel() + "）");
        mobile.setText(subAgentInfo.getMobile());
    }

    private boolean check(){
        if (TextUtils.isEmpty(money.getText())){
            LZToast.getInstance(context).showToast("请输入金额");
            return false;
        }
//        if (Float.valueOf(money.getText().toString()) < -500000){
//            LZToast.getInstance(context).showToast("最低-500000元");
//            return false;
//        }if (Float.valueOf(money.getText().toString()) > 500000){
//            LZToast.getInstance(context).showToast("最高500000元");
//            return false;
//        }
        return true;
    }

    @OnClick(R.id.submit_btn)
    public void onViewClicked() {
        if (!check()){
            return;
        }
        new AlertDialog.Builder(context)
                .setMessage("确定充值吗？")
                .setPositiveButton("确定",(dialog, which) -> {
                    addRecharge();
                    dialog.dismiss();
                }).setNegativeButton("取消",(dialog, which) -> dialog.dismiss())
                .create().show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        findAgentInfo();
    }

    @Override
    public void findAgentInfo() {
        presenter.getAgentInfo(SharePreferenceManager.getInstance().getAgentId(), id);
    }

    @Override
    public void addRecharge() {
        loading.setVisibility(View.VISIBLE);
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
        condition.setSubAgentId(id);
        condition.setMoney(money.getText().toString());
        condition.setImg(GsonManager.getInstance().getGson().toJson(datas));
        condition.setRemark(memo.getText().toString());
        presenter.addRecharge(condition);
    }

    @Override
    public void getAgentInfo(AgentInfo agentInfo) {
        if (agentInfo != null) {
            if (agentInfo.getSubAgentInfo() != null && agentInfo.getSubAgentInfo().size() != 0) {
                this.subAgentInfo = agentInfo.getSubAgentInfo().get(0);
                initData();
            }
        }
    }

    @Override
    public void addResult(Object result) {
        loading.setVisibility(View.GONE);
        showSuccess();
    }

    private void showSuccess(){
        HintDialog dialog = new HintDialog(context,R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth()- LZUtils.dipToPix(context,55)*2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setIcon(R.mipmap.hint_icon_success);
        dialog.setTitle("已完成下级充值");
        dialog.setConfirm("确认");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });
        dialog.getCancelIc().setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });
        dialog.show();
    }

    @Override
    public void uploadForTarget(String tag, File file) {
        uploadPresenter.uploadForTarget(tag,file,progress);
        progress.setVisibility(View.VISIBLE);
        progressLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void uploadResult(String tag, String url) {
        switch (tag){
            case "img":
                datas.add(url);
                imgAdapter.notifyDataSetChanged();
                break;
        }
        progress.setVisibility(View.GONE);
        progressLayout.setVisibility(View.GONE);
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    uploadForTarget("img", new File(selectList.get(0).getCutPath()));
                    break;
            }
        }
    }
}
